# encoding:utf-8
import os
import shutil
import json
import hashlib
import tarfile
import zstandard as zstd

def clean_exist_dir(targets):
    for target_path in targets:
        if os.path.exists(target_path) and os.path.isdir(target_path):
            shutil.rmtree(target_path)
        os.mkdir(target_path)


def extract_tar_zst(archive_path, extract_dir):
    result = os.system(f'tar -xf {archive_path} --zstd -C {extract_dir} "./info/package.json"')
    if result != 0:
        print("can't decompress the file :", archive_path)
    return os.path.join(extract_dir, "info/package.json")


def dump_format_json(json_path, content_json):
    with open(json_path, 'w', encoding='utf-8') as f:
        json.dump(content_json, f, ensure_ascii=False, indent=4)

def compress_file_to_zst(file_path):
    with open(file_path, "rb") as infile:
        with open(f"{file_path}.txt.zst", "wb") as outfile:
            compressor = zstd.ZstdCompressor()
            compressor.copy_stream(infile, outfile)
    hash_value = get_file_hash(f"{file_path}.txt.zst")
    os.system(f"mv {file_path}.txt.zst {file_path}-{hash_value}.txt.zst")
    os.remove(file_path)

def compress_dir_to_zst(target_file_path, source_dir_path):
    normalized_path = source_dir_path.rstrip('/')
    work_dir = os.path.dirname(normalized_path)
    source_dir_name = os.path.basename(normalized_path)
    os.system(f"tar --use-compress-program=zstd -cf {target_file_path} -C {work_dir} {source_dir_name}")
    hash_file_path = target_file_path.replace(".tar.zst", f"-{get_file_hash(target_file_path)}.tar.zst")
    os.system(f"mv {target_file_path} {hash_file_path}")


def get_file_hash(file_path):
    with open(file_path, "rb") as f:
        sha256obj = hashlib.sha256()
        sha256obj.update(f.read())
        return sha256obj.hexdigest()
